import eventEmitter from './eventEmitter';
import store from './store';
import { createRecordTray } from './tray';
const { app, BrowserWindow, ipcMain } = require('electron');
const isDev = require('electron-is-dev');
const path = require('path');
const fs = require('fs');
const { formatVideo, VideoServer } = require('./video');
let mainWindow: Electron.CrossProcessExports.BrowserWindow | null = null;
let readyWindow: Electron.CrossProcessExports.BrowserWindow | null = null;
let playerWindow: Electron.CrossProcessExports.BrowserWindow | null = null;
const commonWindowConfig: any = {
  width: 600,
  height: 400,
  minHeight: 400,
  minWidth: 600,
  titleBarStyle: 'hiddenInset',
  frame: false,
  trafficLightPosition: { x: 10, y: 7 },
  webPreferences: {
    preload: path.join(__dirname, 'preload.js'),
    worldSafeExecuteJavaScript: true,
    nodeIntegration: true,
    contextIsolation: false,
    webviewTag: true
  }
};
function createWindow() {
  console.log('创建主窗口');
  try {
    const win = new BrowserWindow({ ...commonWindowConfig, maxHeight: 600, maxWidth: 800 });
    mainWindow = win;
    store.setState({ mainWindow: win });
    isDev && win?.webContents?.openDevTools?.();
    win.on('close', (e) => {
      e.preventDefault();
      console.log('关闭');
      if (process.platform === 'darwin') {
        // macOS
        console.log('macos隐藏窗口');
        win.hide();
      } else {
        win.minimize();
      }
    });
    isDev
      ? win?.loadURL('http://localhost:9000')
      : win?.loadURL(`file://${path.join(__dirname, '../build/index.html')}`);
  } catch (error) {
    console.log(error, '窗口创建失败');
  }
}
ipcMain.on('operateWindow', (e, type) => {
  switch (type) {
    case 'minimize':
      BrowserWindow.getFocusedWindow()?.minimize();
      break;
    case 'maximize':
      if (BrowserWindow.getFocusedWindow()?.isMaximized()) {
        BrowserWindow.getFocusedWindow()?.unmaximize();
      } else {
        BrowserWindow.getFocusedWindow()?.maximize();
      }
      break;
    case 'close':
      BrowserWindow.getFocusedWindow()?.close();
      break;
  }
});
function createRecorderWindow() {
  console.log('创建录屏小窗');
  mainWindow?.setSize(100, 100, true);
  mainWindow?.setBackgroundColor('rgba(0,0,0,0)');
  mainWindow?.setWindowButtonVisibility(false);
  mainWindow?.setMaximumSize(100, 100);
  mainWindow?.setContentSize(100, 100, true);
  setTimeout(() => {
    mainWindow?.show();
  }, 500);
}
function createReadyWindow() {
  const win = new BrowserWindow({
    ...commonWindowConfig,
    transparent: true,
    backgroundColor: 'rgba(0, 0, 0, 0.2)',
    simpleFullscreen: true,
    alwaysOnTop: true,
    show: false
  });
  store.setState({ readyWindow: win });
  win.on('close', (e) => {
    e.preventDefault();
    console.log('关闭');
    if (process.platform === 'darwin') {
      // macOS
      console.log('macos隐藏窗口');
      win.hide();
    } else {
      win.minimize();
    }
  });
  isDev
    ? win.loadURL('http://localhost:9000/readyRecord.html')
    : win.loadURL(`file://${path.join(__dirname, '../build/readyRecord.html')}`);
  // win.maximize();
  return win;
}
function createPlayerWindow() {
  const win = new BrowserWindow({
    ...commonWindowConfig,
    show: false
  });
  store.setState({ playerWindow: win });
  win.on('close', (e) => {
    e.preventDefault();
    console.log('关闭');
    if (process.platform === 'darwin') {
      // macOS
      console.log('macos隐藏窗口');
      win.hide();
    } else {
      win.minimize();
    }
  });
  isDev
    ? win.loadURL('http://localhost:9000/player.html')
    : win.loadURL(`file://${path.join(__dirname, '../build/player.html')}`);
  // win.maximize();
  return win;
}
ipcMain.on('createRecorderWindow', () => {
  createRecorderWindow();
});
ipcMain.on('downloadFile', (e, { data, cacheDir }) => {
  const base64Data = data;
  const blob = Buffer.from(base64Data, 'binary');
  const exist = fs.existsSync(
    cacheDir ? path.join(cacheDir) : path.join(app.getAppPath(), '/cache')
  );
  if (!exist) {
    fs.mkdirSync(cacheDir ? path.join(cacheDir) : path.join(app.getAppPath(), '/cache'));
  }
  const date = new Date();
  const time =
    date.getFullYear().toString() +
    (date.getMonth() + 1).toString() +
    date.getDate().toString() +
    date.getHours().toString() +
    date.getMinutes().toString();
  if (cacheDir) {
    fs.writeFileSync(path.join(cacheDir, `/${time}.mp4`), blob);
  } else {
    fs.writeFileSync(path.join(app.getAppPath(), `cache/${time}.mp4`), blob);
  }
});
ipcMain.on('getCacheVideo', (e, { cacheDir }) => {
  // 获取缓存的视频
  fs.readdir(
    cacheDir ? path.join(cacheDir) : path.join(app.getAppPath(), '/cache'),
    (_err, data) => {
      const fileList = data?.map((file) => {
        const pathName = cacheDir
          ? path.join(cacheDir, `/${file}`)
          : path.join(app.getAppPath(), `/cache/${file}`);
        return {
          path: `file://${pathName}`,
          name: file
        };
      });
      e.sender.send('getCacheSuccess', fileList);
    }
  );
});
ipcMain.on('openMacSwitch', () => {
  mainWindow?.setMaximumSize(1200, 800);
  mainWindow?.setWindowButtonVisibility(true);
});
ipcMain.on('readyRecord', () => {
  // 打开准备录制窗口
  mainWindow?.hide();
  readyWindow?.setBackgroundColor('rgba(0,0,0,0.2)');
  if (!store.state?.startTray) {
    createRecordTray();
    eventEmitter.emit('start', 'sdds');
  }
  readyWindow?.maximize();
});
ipcMain.on('formatVideo', (e, { fileList, cacheDir, format, encoder }) => {
  fileList.forEach((item) => {
    formatVideo({ source: item.path, format, encoder, cacheDir }, (status) => {
      const progress = {
        id: item.id,
        status
      };
      e.sender.send('formatVideoProgress', progress);
    });
  });
});
ipcMain.on('broadcast', (e, data) => {
  // 广播消息
  mainWindow?.webContents.send('broadcast', data);
});
ipcMain.on('playerVideo', (e, filePath) => {
  console.log('播放视频');
  const videoServer = new VideoServer(filePath);
  videoServer?.start();
  setTimeout(() => {
    playerWindow?.reload();
    playerWindow?.show();
  });
});
app.whenReady().then(() => {
  console.log('启动程序');
  require('@electron/remote/main').initialize();
  require('./globalShotCut');
  require('./menu');
  require('./dock');
  require('./msgCenter');
  require('./tray');
  !mainWindow && createWindow();
  readyWindow = createReadyWindow();
  playerWindow = createPlayerWindow();
  app.on('activate', () => {
    try {
      if (BrowserWindow.getAllWindows().length === 0) {
        !mainWindow && createWindow();
      } else {
        mainWindow?.show();
        console.log('显示窗口');
      }
    } catch (error) {
      console.log(error);
    }
  });
});
app.on('web-contents-created', (e, webContents) => {
  require('@electron/remote/main').enable(webContents);
});
app.on('before-quit', () => {
  app.exit();
});
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});
require('./desktopCapture');
